﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Api.Common
{
    /// <summary>
    /// 参数验证码
    /// </summary>
    public class VcodeHelper
    {
        public static void Create()
        {
            //todo 是否保存在session或cookie中
            var Response = HttpContext.Current.Response;
            Response.AddHeader("Expires", "-1");
            Response.AddHeader("Cache-Control", "no-cache");
            Response.AddHeader("Pragma", "no-cache");

            string result = GenerateCode();
            System.Drawing.Bitmap Img;
            Graphics g;
            MemoryStream ms;
            Img = new Bitmap(180, 60);
            g = Graphics.FromImage(Img);
            Color color = Color.FromArgb(255, 22, 28, 66);
            g.DrawString(result, new Font("Goudy Stout", 22), new SolidBrush(color), 5, 5);
            ms = new MemoryStream();
            Img.Save(ms, ImageFormat.Png);

            Response.Clear();
            Response.ClearContent();
            Response.ContentType = "image/Png";
            Response.BinaryWrite(ms.ToArray());
            g.Dispose();
            Img.Dispose();
            Response.End();
        }

        private static string GenerateCode()
        {
            string str = "A,B,C,D,E,F,G,H,I,J,K,L,N,O,P,Q,R,S,T,U,V,X,Y,Z";
            string[] codes = str.Split(',');
            string result = string.Empty;
            string TempStr = string.Empty;
            Random random = new Random();
            for (int i = 0; i < 4; i++)
            {
                TempStr = codes[random.Next(codes.Length)];
                if (TempStr == codes[codes.Length - 1])
                {
                    str = str.Replace("," + TempStr, string.Empty);
                    codes = str.Split(',');
                }
                else
                {
                    str = str.Replace(TempStr + ",", string.Empty);
                    codes = str.Split(',');
                }
                result += TempStr;
            }
            return result;
        }
    }
}
